package com.dcits.mvc.common.service;

import java.sql.Timestamp;

import com.alibaba.fastjson.JSONObject;
import com.dcits.business.userconfig.UserCommonConfig;
import com.dcits.mvc.base.BaseService;
import com.dcits.mvc.common.model.UserConfig;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class UserConfigService extends BaseService {
	
	public static final UserConfig dao = new UserConfig().dao();
	
	public UserConfig findByKey (String userKey) {
		String sql = "select * from " + UserConfig.TABLE_NAME + " where " + UserConfig.column_user_key + "=?";
		return dao.findFirst(sql, userKey);
	}
	
	public void save (String userKey) {
		Record config = new Record().set(UserConfig.column_user_key, userKey)
				.set(UserConfig.column_config_info_json, JSONObject.toJSONString(UserCommonConfig.defaultSettingInstance()))
				.set(UserConfig.column_create_time, new Timestamp(System.currentTimeMillis()));
		Db.save(UserConfig.TABLE_NAME, config);
	}
	
	public void delbyKey(String userKey) {
		String sql = "delete from " + UserConfig.TABLE_NAME + " where " + UserConfig.column_user_key + "=?";
		Db.delete(sql, userKey);		
	}
	
	public void updateSetting(String userKey, String configJson) {
		findByKey(userKey).set(UserConfig.column_config_info_json, configJson).update();
	}
	
}
